"""
    This file is part of Athedyn's Tale.

    Athedyn's Tale is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Athedyn's Tale is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Athedyn's Tale.  If not, see <http://www.gnu.org/licenses/>.
"""

import time
from rpgObject import rpgObject

class Commands(rpgObject):
    def say(self, args):
        #prints out what the user sent to the function
        print args['message']
        return -1, 0

    def goNorth(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'north':\nUsed to north from your current area.\nUsage: 'north'"
            return -1,0
            
        print "You went north\n"
        newArea = self.objects['area'].statistics['exits']['north']
        return newArea, 0

    def goSouth(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'south':\nUsed to go south from your current area.\nUsage: 'south'"
            return -1,0
            
        print "You went south\n"
        newArea = self.objects['area'].statistics['exits']['south']
        return newArea, 0

    def goEast(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'east':\nUsed to go east from your current area.\nUsage: 'east'"
            return -1,0
            
        print "You went east\n"
        newArea = self.objects['area'].statistics['exits']['east']
        return newArea, 0

    def goWest(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'west':\nUsed to go west from your current area.\nUsage: 'west'"
            return -1,0
            
        print "You went west\n"
        newArea = self.objects['area'].statistics['exits']['west']
        return newArea, 0

    def look(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'look':\nUsed to look in a direction.  You can look at the current area by only using 'look'.\nUsage: 'look DIRECTION'"
            return -1,0
            
        if args['message'] == "look":
            self.objects['area'].printDescription()
            return -1,0
        #try:
        if self.objects['area'].statistics['exits'][args['message']] > 0:
            ID = self.objects['area'].statistics['exits'][args['message']]
            if str(ID)[0:2] == '99':
                if len(str(ID)) >= 3:
                    location = self.objects['area'].statistics['zones'][int(str(ID)[2:len(str(ID))])]
            else:
                location = self.objects['area'].statistics['names'][self.objects['area'].statistics['exits'][args['message']]]
            print "To the %s is %s" % (args['message'], location)
            return -1,0
        #except:
        #    pass
        print "There is no exit this direction"
        return -1,0

    def attack(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'attack':\nUsed to attack the enemy in the area.\nUsage: 'attack'"
            return -1,0
            
        timeBetween = int(time.time()) - self.objects['area'].statistics['respawnLast'][self.objects['area'].ID] + self.objects['enemy'].statistics['randomRespawn']
        if timeBetween > self.objects['enemy'].statistics['respawnTime'][self.objects['area'].statistics['enemyID']]:
            self.objects['area'].Continue = 1
            return -1, 1
        else:
            print "Nothing here"
            return -1, 0

    def inventory(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'inventory':\nUsed to show all of the items in your current inventory.\nUsage: 'inventory'"
            return -1,0
            
        self.objects['user'].items()
        return -1,0

    def use(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'use':\nUsed to use items from your inventory.\nUsage: 'use ITEM'"
            return -1,0
            
        for item in self.objects['user'].statistics['inventory']:
            #matches the user submited word with items in the inventory
            if args['message'].lower() == self.objects['items'].statistics['names'][int(item)].lower():
                #prints what they used if a match found
                print "You used %s" % self.objects['items'].statistics['names'][int(item)]
                #attemps to find out if anything actually can be done with the item, such has using a weapon... on what?  First looks into the items object for the effect of the item's ID.  comes out a string, needs to be an int
                if int(self.objects['items'].statistics['itemEffect'][int(item)][0]) == 0:
                    print "But nothing happened"
                    #checks to see if in battle and returns 0 so the user still has a chance to do something since this didn't work
                    if self.objects['attack'].statistics['inBattle'] == 1:
                        return 0
                    return -1,0
                #sends the item id off to the effect method in Items instance so that it can do what it needs to
                self.objects['items'].effect(int(item))
                #removes the object after it is used from the inventory
                self.objects['user'].statistics['inventory'].remove(item)
                #checks to see if they were in battle and deals accordingly
                if self.objects['attack'].statistics['inBattle'] == 1:
                    return 1
                return -1,0
        #are they in battle?  if so...
        if self.objects['attack'].statistics['inBattle'] == 1:
            return 1
        return -1,0

    def cast(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'cast':\nUsed to cast a spell that you know.\nUsage: 'cast SPELL'"
            return -1,0
            
        for spell in self.objects['magic'].statistics['castWord']:
            key = self.objects['magic'].statistics['castWord'].index(spell)
            if args['message'].lower() == spell.lower():
                if self.objects['user'].statistics['spellList'].count(key) > 0:
                    if self.objects['attack'].statistics['inBattle'] == 0:
                        if self.objects['magic'].statistics['inBattle'][key] == 0:
                            self.objects['magic'].effects(key)
                        else:
                            print "Can't use this out of battle"
                    if self.objects['attack'].statistics['inBattle'] == 1:
                        self.objects['magic'].effects(key)
                else:
                    print "Unknown spell"
                    if self.objects['attack'].statistics['inBattle'] == 1:
                        return 0
                    return -1,0
        if self.objects['attack'].statistics['inBattle'] == 1:
            return 1
        return -1,0
     
    def spells(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'spells':\nUsed to show all of your current spells.\nUsage: 'spells'"
            return -1,0
        print "Your spell list:"
        for spell in self.objects['user'].statistics['spellList']:
            print self.objects['magic'].statistics['names'][spell]
        return -1,0
    
    def status(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'status':\nUsed to show your current status.\nUsage: 'status'"
            return -1,0
        self.objects['user'].status(2)
        return -1,0

    def save(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'save':\nUsed to save your game.\nUsage: 'save'"
            return -1,0
        self.objects['main'].save()
        return -1,0

    def take(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'take':\nUsed to take items from the current area.\nUsage: 'take ITEM'"
            return -1,0
        for item in self.objects['user'].statistics['areaItems'][self.objects['area'].zoneID][self.objects['area'].ID]:
            if args['message'].lower() == self.objects['items'].statistics['names'][int(item)].lower():
                print "Taken a %s" % self.objects['items'].statistics['names'][int(item)]
                self.objects['user'].statistics['inventory'].append(int(item))
                self.objects['user'].statistics['areaItems'][self.objects['area'].zoneID][self.objects['area'].ID].remove(item)              
        #print args['message'].lower()
        return -1,0
    
    def give(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'give':\nUsed to give NPCs items.\nUsage: 'give ITEM PERSON'"
            return -1,0
            
        try:
            keyItem = args['message'].split()[0]
            person = args['message'].split()[1]
        except:
            print "Give what to whom?"
            return -1,0
            
        for item in self.objects['items'].statistics['names']:
            if keyItem.lower() == item.lower():
                key = self.objects['items'].statistics['names'].index(item)
        
        for quest in self.objects['area'].statistics['special']:
            if int(quest[0]) == 1:
                if person.lower() == self.objects['quest'].statistics['giver'][int(quest[1])].lower():
                    questID = int(quest[1])
        try:
            self.objects['quest'].give(questID, key)
        except:
            print "No such item or person"
        return -1,0
    
    def map(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'map':\nUsed to show the current zone's map.  Only what you have explored is shown.\nUsage: 'map'"
            return -1,0
            
        self.objects['area'].map()
        return -1,0
        
    def talk(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'talk':\nUsed to talk to people in the game.\nUsage: 'talk PERSON'"
            return -1,0
            
        for item in self.objects['quest'].statistics['giver']:
            if args['message'].lower() == item.lower():
                key = self.objects['quest'].statistics['giver'].index(item)
                self.objects['quest'].printQuest(key)
        for person in self.objects['shop'].statistics['owner']:
            if args['message'].lower() == person.lower():
                key = self.objects['shop'].statistics['owner'].index(person)
                self.objects['shop'].list(key)
        return -1,0
        
    def buy(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'buy':\nUsed to purchase goods from stores.  If an item has more than one word, use the first word only.\nUsage: 'buy ITEM PERSON'"
            return -1,0
        
        #makes sure the user typed in the correct number of words    
        try:
            #first word is the item buying
            keyItem = args['message'].split()[0]
            #second word is the seller
            person = args['message'].split()[1]
        except:
            #if they didn't type it right they get this error
            print "Buy what from who?"
            return -1,0
        
        
        #goes through the names of items to get the correct ID of the item that is being purchased
        for item in self.objects['items'].statistics['names']:
            #matches the items by taking the lower case of them
            #this is in case there are more than one word.  just use the first word of the item
            if len(item.split()) > 1:
                if keyItem.lower() == item.split()[0].lower():
                    #saves the item ID to key
                    key = self.objects['items'].statistics['names'].index(item)
            else:
                if keyItem.lower() == item.lower():
                    #saves the item ID to key
                    key = self.objects['items'].statistics['names'].index(item)
        
        for shop in self.objects['area'].statistics['special']:
            #check to see if there is a shop in the area
            if int(shop[0]) == 2:
                #check to see if the owner of the shop is correct
                if person.lower() == self.objects['shop'].statistics['owner'][int(shop[1])].lower():
                    #searches through the items in the shop
                    for item in self.objects['shop'].statistics['items'][int(shop[1])]:
                        #if the ids match, then you bought it
                        if key == item:
                            self.objects['shop'].buy(key)
                            return -1,0
        print "They don't sell that."
        return -1,0

    def sell(self,args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'sell':\nUsed to sell goods to stores.\nUsage: 'sell ITEM PERSON'"
            return -1,0
        
        #attempts to see if the person typed in the correct number of words.  ITEM (sell to) PERSON    
        try:
            #first word is the item
            keyItem = args['message'].split()[0]
            #second word is the person buying
            person = args['message'].split()[1]
        except:
            #if they didn't type it right, then spits this error
            print "Sell what to who?"
            return -1,0
        
        #goes through the names of items to get the correct ID of the item that is being sold
        for item in self.objects['items'].statistics['names']:
            #matches the items by taking the lower case of them 
            if keyItem.lower() == item.lower():
                #saves the item ID to key
                key = self.objects['items'].statistics['names'].index(item)
        
        for shop in self.objects['area'].statistics['special']:
            #check to see if there is a shop in the area
            if int(shop[0]) == 2:
                #check to see if the owner is the person they said
                if person.lower() == self.objects['shop'].statistics['owner'][int(shop[1])].lower():
                    #check to see what type of shop it is, as to block weapons to sell to an item shop etc
                    #items
                    if self.objects['shop'].statistics['type'][int(shop[1])] == 1:
                        #checking to see if it is an item
                        if int(self.objects['items'].statistics['itemEffect'][key][0]) > 0:
                            self.objects['shop'].sell(key)
                            return -1,0
                    #weapon
                    if self.objects['shop'].statistics['type'][int(shop[1])] == 2:
                        #checking to see if it is an item
                        if int(self.objects['items'].statistics['weaponType'][key][0]) > 0:
                            self.objects['shop'].sell(key)
                            return -1,0
                    print "%s does not accept this item." % self.objects['shop'].statistics['owner'][int(shop[1])]
        
        return -1,0
    
    def quit(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        if args['message'] == "help":
            print "Help 'quit':\nUsed to quit the game.  Chance to save before quitting.\nUsage: 'quit'"
            return -1,0
            
        #checks if they really want to quit
        yesNo =  raw_input("Are you sure you wish to quit?(yes/no) ")
        if yesNo == 'yes':
            #do they want to save?
            saveYesNo = raw_input("Do you wish to save first?(yes/no) ")
            if saveYesNo == 'yes':
                #saves file if yes
                self.objects['main'].save()
            #sets the variable that keeps the main loop going to 0 and killing the loop
            self.objects['area'].Continue = 0
            return -1,0
        else:
            return -1,0

    def help(self, args):
        #checks to see if someone invoked it asking for help.  Prints out help string
        
        if args['message'] == "help":
            print "The commands available are: "
            commands = ""
            #makes a list of all of the commands available to a user
            for key, function in self.objects['area'].commands.items():
                commands = commands + " " + key
            print commands
            print "To find out more about these commands, type 'help COMMAND'"
            return -1,0
        #prints out the help message from each command
        #loops through all of the commands
        for key, function in self.objects['area'].commands.items():
            #stops at the command they wanted
            if args['message'] == key:
                #sends the command the "help" attribute
                args['message'] = "help"
                function(args)
                return -1,0
        return -1,0
